package top.rainf.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.rainf.domain.vo.ChatRecord;
import top.rainf.mapper.ChatRecordMapper;
import top.rainf.service.IChatRecordService;

import java.util.LinkedList;
import java.util.List;

/**
 * @author 星环
 * @date Wed May 10 21:04:41 CST 2023
 * @description ChatRecord服务的实现类
 */
@Service
public class ChatRecordService implements IChatRecordService {

    @Autowired
    ChatRecordMapper chatRecordMapper;

    @Override
    public List<ChatRecord> getChatRecordList() {
        return chatRecordMapper.selectAll();
    }



    @Override
    public ChatRecord getOneById(int id) {
        return chatRecordMapper.selectById(id);
    }

    @Override
    public boolean deleteOneById(int id) {
        return chatRecordMapper.deleteById(id) == 1;
    }

    @Override
    public boolean deleteAll(List<Integer> idList) {
        return chatRecordMapper.deleteByIds(idList) == idList.size();
    }

    @Override
    public boolean updateById(ChatRecord chatRecord) {
        return chatRecordMapper.updateById(chatRecord) == 1;
    }

    @Override
    public List<ChatRecord> getListByUserId(int userId, int friendId) {
        List<ChatRecord> recordList = chatRecordMapper.selectByUserId(userId, friendId);
        if(recordList.size() == 0){
            return recordList;
        }
        List<Integer> list = new LinkedList<>();
        recordList.forEach(record-> {
            //是对方发来的消息，设为已读
            if (record.getSenderId1() == friendId) {
                list.add(record.getId());
            }
        });
        //设为已读
        chatRecordMapper.readMsg(list);
        return recordList;
    }

    @Override
    public List<ChatRecord> getNewMessage(int userId, int friendId) {
        List<ChatRecord> recordList = chatRecordMapper.selectNewMsg(userId,friendId);
        if(recordList.size() == 0){
            return recordList;
        }
        List<Integer> list = new LinkedList<>();
        recordList.forEach(record->list.add(record.getId()));
        //设为已读
        chatRecordMapper.readMsg(list);
        return recordList;
    }


    @Override
    public void sendMsg(int userId, int friendId, String msg) {
        chatRecordMapper.sendMessage(userId,friendId,msg);
    }
}
